package com.easy.common.interceptors;


import cn.hutool.core.util.ObjectUtil;
import com.easy.common.api.CommonResult;
import com.easy.common.api.ResultCode;
import com.easy.common.util.JsonUtil;
import com.easy.domain.User;
import com.easy.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户操作拦截器
 * @author 风亦未止
 * @date 2021/9/20 22:44
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 这里不进行@Autowired注入，因为会空指针异常，通过拦截器注入再通过构造器传递就不会有该异常。
     */
    private SessionService sessionService;

    public UserInterceptor(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        log.info("拦截器走起~");
        String cookie = request.getHeader("cookie");
        //截取sessionId
        String sessionId = null;
        try {
            sessionId = cookie.substring(cookie.indexOf("JSESSIONID=")+11,cookie.indexOf("JSESSIONID=")+43);
        } catch (Exception e) {
            String error = JsonUtil.toJSON(CommonResult.failed(ResultCode.UNAUTHORIZED));
            try {
                writer = response.getWriter();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            writer.print(error);
            log.info(error);
            return  false;
        }
        log.info(cookie);
        log.info("sessionId: "+sessionId);
        User user = (User) sessionService.getSession(sessionId);
        if (ObjectUtil.isNull(user)){
            String error = JsonUtil.toJSON(CommonResult.failed(ResultCode.UNAUTHORIZED));
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.print(error);
            log.info(error);
            //和上面的writer冲突了。
            //Asserts.fail("未登录，请先登录！");
            return  false;
        }
        String openid = user.getOpenid();
        log.info("用户openid："+openid+"已登录！");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
